package cn.com.xjnt.vas.web.ordering.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.frameworks.core.logger.annotation.RunLogger;
import com.frameworks.core.web.controller.BaseController;
import com.frameworks.core.web.page.WebPage;
import com.frameworks.core.web.result.DataResult;
import com.frameworks.core.web.result.MsgResult;
import com.frameworks.core.web.search.DynamicSpecifications;
import com.google.common.collect.Lists;

import cn.com.xjnt.vas.ordering.domain.entity.FoodMenu;
import cn.com.xjnt.vas.ordering.domain.vo.FoodMenuVo;
import cn.com.xjnt.vas.ordering.service.FoodMenuService;

/**
 * 类说明：
 * 
 * @author 作者 LUXIN
 * @version 创建时间：2016年5月13日16:37:27
 */
@Controller
@RequestMapping("/manage/ordering/foodMenu")
public class FoodMenuController extends BaseController {

    private static final String VIEW_PAGE = "ordering/foodMenu/view";
    private static final String FORM_PAGE = "ordering/foodMenu/form";
    private static final String SELECT_PAGE = "ordering/foodMenu/select";

    @Autowired
    private FoodMenuService foodMenuService;
    @Autowired
    private Mapper mapper;

    protected FoodMenuService getService() {
        return foodMenuService;
    }

    /**
     * view页面
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Order:foodMenu:show" })
    @RequestMapping(value = "", method = { RequestMethod.GET })
    public ModelAndView show(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView(VIEW_PAGE);
        mav.addObject("organizationId",getLoginUser().getOrganization().getId());//数据权限
        return mav;
    }
    
    /**
     * select页面
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Order:hospital:show" })
    @RequestMapping(value = "/select", method = { RequestMethod.GET })
    public ModelAndView select(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView(SELECT_PAGE);
        mav.addObject("organizationId",getLoginUser().getOrganization().getId());//数据权限
        return mav;
    }
    
    /**
     * view页面list方法
     * 
     * @param request
     * @param webPage
     * @return
     */
    @RequiresPermissions(value = { "Order:foodMenu:show" })
    @RequestMapping(value = "/list", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult list(HttpServletRequest request, WebPage webPage) {
        DataResult dataRet = new DataResult();
        try {
            Specification<FoodMenu> specification = DynamicSpecifications.bySearchFilter(request, FoodMenu.class);
            List<FoodMenu> models = getService().findByCondition(specification, webPage);
            List<FoodMenuVo> lstVo = Lists.newArrayList();
            for (FoodMenu model : models) {
                FoodMenuVo vo = mapper.map(model, FoodMenuVo.class);
                lstVo.add(vo);
            }
            dataRet.pushOk("获取数据列表成功！");
            dataRet.setTotal(webPage.getTotalCount());
            dataRet.setRows(lstVo);
        } catch (Exception e) {
            dataRet.pushError("获取数据列表失败！");
            logger.error("获取数据列表异常！", e);
        }
        return dataRet;
    }

    /**
     * 新增
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Order:foodMenu:show" })
    @RequestMapping(value = "/add", method = { RequestMethod.GET })
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView(FORM_PAGE);
        mav.addObject("organizationId",getLoginUser().getOrganization().getId());//数据权限
        return mav;
    }

    /**
     * 修改
     * 
     * @param id
     * @return
     */
    @RequiresPermissions(value = { "Order:foodMenu:show" })
    @RequestMapping(value = "/edit/{id}", method = { RequestMethod.GET })
    public ModelAndView edit(@PathVariable("id") Long id) {
        ModelAndView mav = new ModelAndView(FORM_PAGE);
        FoodMenu model = getService().findById(id);

        mav.addObject("foodMenu", model);
        mav.addObject("organizationId",getLoginUser().getOrganization().getId());//数据权限
        return mav;
    }

    /**
     * 保存
     * 
     * @param entity
     * @return
     */
    @RunLogger(value = "添加菜单", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:foodMenu:add" })
    @RequestMapping(value = "/store", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult store(FoodMenu entity,
            @RequestParam(value = "bgImgFile") MultipartFile[] bgImg,
            @RequestParam(value = "focusImgFile") MultipartFile[] focusImg,
            @RequestParam(value = "cornerImgFile") MultipartFile[] cornerImg) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().saveFoodMenu(entity, bgImg, focusImg, cornerImg);
            msgRet.pushOk("添加成功！");
        } catch (Exception e) {
            msgRet.pushError("添加失败：" + e.getMessage());
            logger.error("添加时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 更新
     * 
     * @param entity
     * @return
     */
    @RunLogger(value = "编辑菜单", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:foodMenu:modify" })
    @RequestMapping(value = "/edit", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult modify(FoodMenu entity,
            @RequestParam(value = "bgImgFile") MultipartFile[] bgImg,
            @RequestParam(value = "focusImgFile") MultipartFile[] focusImg,
            @RequestParam(value = "cornerImgFile") MultipartFile[] cornerImg) {
        MsgResult msgRet = new MsgResult();
        try {
            entity.setCreateTime(getService().findById(entity.getId()).getCreateTime());
            getService().updateFoodMenu(entity, bgImg, focusImg, cornerImg);
            msgRet.pushOk("修改成功!");
        } catch (Exception e) {
            msgRet.pushError("修改失败：" + e.getMessage());
            logger.error("修改时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 删除
     * 
     * @param id
     * @return
     */
    @RunLogger(value = "删除菜单", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:foodMenu:remove" })
    @RequestMapping(value = "/remove/{id}", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult remove(@PathVariable("id") Long id) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().deleteById(id);
            msgRet.pushOk("删除成功！");
        } catch (Exception e) {
            msgRet.pushError("删除失败：" + e.getMessage());
            logger.error("删除时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 批量删除
     * 
     * @param ids
     * @return
     */
    @RunLogger(value = "批量删除菜单", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:foodMenu:remove" })
    @RequestMapping(value = "/remove", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult remove(@RequestParam("ids[]") Long[] ids) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().deleteByIds(ids);
            msgRet.pushOk("批量删除成功!");
        } catch (Exception e) {
            msgRet.pushError("批量删除失败：" + e.getMessage());
            logger.error("批量删除时，发生异常！", e);
        }
        return msgRet;
    }
    
    /**
     * 下载附件
     * @param id 
     * @param type 1:背景图 2：焦点图 3：角标图
     * @param res
     * @return
     */
    @RequestMapping(value = "/downloadImg", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult downloadImg(Long id,int type,HttpServletResponse res){
        MsgResult msgRet = new MsgResult();
        try {
            FoodMenu model = getService().findById(id);
            String path = "";
            String name = "";
            switch (type) {
            case 1:
                path = model.getBgImg();
                name = model.getBgName();
                break;
            case 2:
                path = model.getFocusImg();
                name = model.getFocusName();
                break;
            case 3:
                path = model.getCornerImg();
                name = model.getCornerName();
                break;
            }
            File file = new File(path);
            if (!file.exists()) {
                msgRet.pushError("文件不存在。");
                return msgRet;
            }
            InputStream ins = new FileInputStream(path);
            res.reset();
            res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(name, "UTF-8"));
            res.setContentType("application/octet-stream; charset=utf-8");
            byte[] b = new byte[100];
            int len = 0;
            OutputStream os = res.getOutputStream();
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            ins.close();
            msgRet.pushOk("下载成功");
        } catch (Exception e) {
            msgRet.pushError("下载附件失败：" + e.getMessage());
            logger.error("下载附件时，发生异常！", e);
        }
        return msgRet;
    }
    /**
     * 删除附件
     * @param id
     * @param type
     * @return
     */
    @RequestMapping(value = "/deleteImg", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult deleteImg(Long id,int type){
        MsgResult msgRet = new MsgResult();
        try {
            FoodMenu model = getService().findById(id);
            String path = "";
            switch (type) {
            case 1:
                path = model.getBgImg();
                model.setBgImg("");
                model.setBgName("");
                model.setBgUrl("");
                break;
            case 2:
                path = model.getFocusImg();
                model.setFocusImg("");
                model.setFocusName("");
                model.setFocusUrl("");
                break;
            case 3:
                path = model.getCornerImg();
                model.setCornerImg("");
                model.setCornerName("");
                model.setCornerUrl("");
                break;
            }
            File file = new File(path);
            if (!file.exists()) {
                logger.info("文件不存在");
            } else {//文件存在
                getService().deleteImg(path);//物理删除文件
            }
            
            msgRet.pushOk("文件删除成功");
            getService().update(model);
            
        } catch (Exception e) {
            msgRet.pushError("删除附件失败：" + e.getMessage());
            logger.error("删除附件时，发生异常！", e);
        }
        return msgRet;
    }
}
